package app.ui;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.google.android.maps.GeoPoint;

import database.local.Business;
import database.local.DataBaseClient;
import database.local.Deal;
import database.local.OpeningWindowSyncronizer;
import database.local.QueryData;
import database.local.Utils;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ViewFlipper;

public class OpeningActivity extends Activity {
	private static OpeningActivity instance;
	private Button toMapBtn, prefsBtn;
	public ViewFlipper flip;
	private LocationManager lm;
	private String bestProvider;
	private Location location;
	private List<Business> business_list;
	private OpeningWindowSyncronizer dbc;
	public DataBaseClient dbcc;
	private int deal_index;
	private DetailPopupLayoutData dpld;

	//final static int SHOW_PREFERENCES = AndroAppActivity.SHOW_PREFERENCES;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.opening_screen);
		
		instance = this;
		dbcc = new DataBaseClient(this);

		// ---- find current location -------- //
		lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		Criteria crit = new Criteria();
		crit.setAccuracy(Criteria.ACCURACY_FINE);
		crit.setHorizontalAccuracy(Criteria.ACCURACY_HIGH);
		crit.setSpeedRequired(false);
		crit.setCostAllowed(true);
		crit.setPowerRequirement(Criteria.POWER_LOW);
		crit.setBearingRequired(false);

		bestProvider = lm.getBestProvider(crit, true);

		//Log.w("LocationProvider", bestProvider);

		if (bestProvider!=null)
			location = lm.getLastKnownLocation(bestProvider);
		
		if (location == null) {
			Log.e("LocationBug",
					"Location Instalization Bug - swithing to network");
			bestProvider = LocationManager.NETWORK_PROVIDER;
			location = lm.getLastKnownLocation(bestProvider);
		}
		if (location != null) {
			Double lat = location.getLatitude() * 1E6;
			Double lng = location.getLongitude() * 1E6;
			GeoPoint p = new GeoPoint(lat.intValue(), lng.intValue());
		}

		// ----- sync with server -------------- //
		Calendar c = Calendar.getInstance();
		Date currentDate = c.getTime();
		// String date = pad(currentDate.getDate()) + "/" +
		// pad(currentDate.getMonth()) + "/" + pad(currentDate.getYear());

		int bitMapDay = AndroAppActivity.intDayToBitmap(currentDate.getDay());
		int min = currentDate.getMinutes();
		int hour = currentDate.getHours();
		String time = Utils.pad(hour) + ":" + Utils.pad(min);
		String strDay = String.valueOf(bitMapDay);

		// Sync with server
		Log.i("Time", "time query :" + time);
		dbc = new OpeningWindowSyncronizer(this);
		dbc.sync("Israel", "Tel Aviv", Integer.toString(QueryData.ALL_TYPES),
				strDay, time, "2");

		toMapBtn = (Button) findViewById(R.id.opening_screen_to_map_btn);
		prefsBtn = (Button) findViewById(R.id.opening_screen_preferences_btn);
		flip = (ViewFlipper) findViewById(R.id.opening_screen_flip);

		// ----- fields instalization --------------//

		toMapBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent i = new Intent(OpeningActivity.this,
						AndroAppActivity.class);
				startActivity(i);
			}
		});

		prefsBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent i = new Intent(OpeningActivity.this,
						PreferencesActivity.class);
				startActivity(i);
			}
		});


		// specify flipping interval
		Animation slideLeftIn = AnimationUtils.loadAnimation(this,
				R.anim.view_transition_in_left);
		Animation slideRightOut = AnimationUtils.loadAnimation(this,
				R.anim.view_transition_out_right);

		// flip.setInAnimation(this, android.R.anim.slide_in_left);
		// flip.setOutAnimation(this, android.R.anim.slide_out_right);

		flip.setInAnimation(slideLeftIn);
		flip.setOutAnimation(slideRightOut);
		flip.setFlipInterval(5000);
		flip.setAutoStart(true);

		slideLeftIn.setAnimationListener(new AnimationListener() {

			public void onAnimationStart(Animation animation) {
				initiateDPLD();
				// use the item title to get the business from the business
				// list.
				if ((business_list!=null) &&  !business_list.isEmpty()) {
					if (deal_index >= business_list.size()){
						deal_index = 0;
					}
					final Business b = business_list.get(deal_index);
					// get the first deal from the deals' list
					if (b != null && b.getDeals() != null) {
						final Deal d = b.getDeals().get(0);
						deal_index++;
						fillDetailsForBusiness(d,b,dpld);
					}
				}
				else
				{
					Log.w("OpenningWindow", "Business is empty");
				}
			}

			public void onAnimationRepeat(Animation animation) {
			}

			public void onAnimationEnd(Animation animation) {
			}

		});

	}

	/**
	 * Handling all the returns from other activities.
	 */
//	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//		super.onActivityResult(requestCode, resultCode, data);
//
//		switch (requestCode) {
//		case SHOW_PREFERENCES:
//			Log.i("OpeningAct", "Back from preferences");
//			break;
//		}
//	}

	public void setBusiness_list(List<Business> business_list) {
		this.business_list = business_list;
	}

	private void fillDetailsForBusiness(Deal d, Business b,
			DetailPopupLayoutData dpld) {
		dpld.setDNameText(d.getShortName());
		dpld.setBNameText(b.getName());
		dpld.setAddressText(b.getFullAddress());
		dpld.setRate(d.getRate());
		dpld.setMoney(d.getCostLevel());
		dpld.setDistanceText(Utils.getDistanceStr(b.getDistance()));
		

		dpld.setImage(d, this);
		final Business fb = b;
		dpld.getLayout().setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
//				Intent toMapIntent = new Intent(OpeningActivity.this,
//						AndroAppActivity.class);
//				toMapIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
//
//				Bundle bundle = new Bundle();
//				bundle.putParcelable("business", fb);
//
//				toMapIntent.putExtra("values", bundle);
//
//				OpeningActivity.this.startActivity(toMapIntent);
				
				openDealWindow(fb, fb.getDeals().get(0));
			}
		});

		dpld.setVisibilty(true);
	}

	private void initiateDPLD() {
		dpld = new DetailPopupLayoutData();

		View currentView = findViewById(android.R.id.content);
		dpld.attachAddressToView(currentView,
				R.id.opening_screen_detailes_address_text);
		dpld.attachBNameToView(currentView,
				R.id.opening_screen_detailes_business_name_text);
		dpld.attachDNameToView(currentView,
				R.id.opening_screen_detailes_deal_name_text);
		dpld.attachImageToView(currentView, R.id.opening_screen_detailes_image);
		dpld.attachLayoutToView(currentView,
				R.id.opening_screen_detailes_layout);
		dpld.attachMoneyToView(currentView,
				R.id.opening_screen_detailes_money_ratingbar);
		dpld.attachRateToView(currentView,
				R.id.opening_screen_detailes_stars_ratingbar);
		dpld.attachDistanceToView(currentView,
				R.id.opening_screen_detailes_distance_text);
	}
	protected void openDealWindow(Business b, Deal d) {
		Intent openDealActivity = new Intent(this, DealViewActivity.class);
		Bundle bundle = new Bundle();
		
		bundle.putParcelable("deal", d);
		bundle.putParcelable("business", b);
		
		openDealActivity.putExtra("values", bundle);
		this.startActivity(openDealActivity);
	}

	public static OpeningActivity getInstance() {
		return instance;
	}
}
